<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 文件轨迹模型
 * @author Calvin
 */
class File_trace_model extends MY_Model {


	function __construct()
	{
		parent::__construct();
	}

	//获取最后插入id
	public function get_insert_id()
	{
		return $this->db->insert_id();
	}

	/**
	 * 获取文件轨迹
	 * @param $fid 文件ID
	 * @param array $condition 条件
	 * @param string $fields 所需字段
	 * @param bool $limit 条数
	 * @param string $group
	 * @return mixed
	 */
	public function get_traces($fid,$condition=array(),$sort="ts",$direction="desc",$fields="id,actor
,event,start,end,relation,ts,unsafe,hidden,file_id,actor_ip,actor_city",$limit=false,$group="")
	{
		if(isset($condition['date']))
		{
			$s1 = strtotime($condition['date']." 00:00:00");
			$s2 = strtotime($condition['date']." 23:59:59");
			$this->db->where("ts BETWEEN $s1 AND $s2");
			unset($condition['date']);
		}
		$condition['file_id']=$fid;
		if($limit!==false && $limit!=='')
		{
			$limit_arr = !is_array($limit)?explode(",",$limit):$limit;
			isset($limit_arr[1])?$this->db->limit($limit_arr[1],$limit_arr[0]):$this->db->limit($limit_arr[0]);
		}

		if(!empty($group))
		{
			$this->db->group_by($group);
		}
		$order = $sort." ".$direction;
		if($sort!="id")
		{
			$order .=",id ".$direction;
		}
		$rows = $this->db->select($fields)->order_by($order)->get_where(self::TB_FILE_TRACES,$condition)->result_array();
		//var_dump($this->db->last_query());exit;
		return !empty($rows)?array("rows"=>$rows,"total"=>count($rows)):null;
	}

	/**
	 * 获取文件轨迹的文件
	 * @param $uid
	 * @param array $file_condition
	 * @param string $sort
	 * @param string $direction
	 * @param string $file_fields
	 * @param bool $limit
	 * @param string $active
	 * @return array|null
	 */
	public function get_trace_files($uid,$file_condition=array(),$sort="ts",$direction="desc",$file_fields="id,name",$limit=false,$active="")
	{
		if(empty($uid) || empty($file_condition) || !is_array($file_condition) || empty($file_fields))
		{
			return null;
		}
		if(!empty($file_condition))
		{
			$file_condition = Common::array_key_fill($file_condition,"file.");
		}

		if(!is_array($file_fields))
		{
			$file_fields=explode(",",$file_fields);
		}
		$select_fields=array();
		foreach($file_fields as $k=>$v)
		{
			$select_fields[]="file.".$v;
		}
		if($limit!==false && $limit!=='')
		{
			$limit_arr = !is_array($limit)?explode(",",$limit):$limit;
			isset($limit_arr[1])?$this->db->limit($limit_arr[1],$limit_arr[0]):$this->db->limit($limit_arr[0]);
		}
		$this->db->where("file.uid",$uid);
		$select_fields[]="type.ext_name";
		if($sort=="ts")
		{
			$sort = "ts_order";
			$select_fields[]="max(trace.ts) as ts_order";
		}
		else
		{
			$sort = "file.".$sort;
		}
		if(!empty($active))
		{
			$select_fields[]="(file.id={$active}) as active";
			$this->db->order_by("active desc,".$sort." ".$direction);
		}
		else
		{
			$this->db->order_by($sort,$direction);
		}
		$this->db
			->select($select_fields)
			->from(self::TB_FILE_TRACES." trace")
			->join(self::TB_USER_FILES." file","file.id=trace.file_id")
			->join(self::TB_FILE_TYPE." type","type.id=file.type")
			->where($file_condition)
			->group_by("trace.file_id");
			//->distinct();
		$rows = $this->db->get()->result_array();
		//$test = $this->db->last_query();
		//var_dump($direction);exit;
		return !empty($rows)?array("rows"=>$rows,"total"=>count($rows)):null;
	}

	public function add_trace($data)
	{
		return $this->db->insert(self::TB_FILE_TRACES,$data);
	}

	public function add_traces($data)
	{
		return $this->db->insert_batch(self::TB_FILE_TRACES,$data);
	}

	/**
	 * 获取轨迹列表
	 * @param $fid
	 * @param $where
	 * @param $limit
	 * @param string $i_field
	 * @return array|null
	 */
	public function get_trace_list($fid, $where, $limit, $i_field='') {
		//字段处理
		if (empty($i_field))
			$i_field = array('id', 'actor', 'event', 'ts', 'unsafe', 'file_id', 'actor_ip', 'actor_city');

		if (is_string($i_field))
			$i_field = explode(',', $i_field);

		$field = '';
		foreach ($i_field as $k => $v) {
			$field .= 't.'.$v.',';
		}
		$field_add = "nickname, mobile, email, GROUP_CONCAT(CONCAT_WS('/',t2.id,t2.event,t2.start,t2.end)) as traces";
		$this->db->select($field.$field_add, false);

		//where
		if (! empty($where)) {
			if (is_string($where)) {
				$where = explode(',', $where);
			}

			$where_arr = Common::array_key_fill($where, 't.');
			$this->db->where($where_arr);
		}

		//limit
		if (! empty($limit)) {
			$limit_arr = !is_array($limit) ? explode(",",$limit) : $limit;
			isset($limit_arr[1]) ? $this->db->limit($limit_arr[1],$limit_arr[0]) : $this->db->limit($limit_arr[0]);
		}

		$this->db->where('t.file_id', $fid);

		$this->db->from(self::TB_FILE_TRACES." t")
				->join(self::TB_FILE_TRACES." t2", "t2.relation = t.id", 'left')
				->join(self::TB_USER." u","u.id = t.actor", 'left')
				->group_by('t.id')
				->order_by('ts desc, id desc');

		$rows = $this->db->get()->result_array();
		//echo $this->db->last_query();die;
		return !empty($rows) ? array("rows"=>$rows,"total"=>count($rows)) : null;
	}
}
